//
//  ZMParser+Json.m
//  EIP
//
//  Created by mac on 15/3/19.
//  Copyright (c) 2015年 Leo. All rights reserved.
//

#import "NSObject+Function.h"

#import <objc/runtime.h>

#define Prefix @"xs_"

@implementation NSObject(Function)

- (void)kk_parserJsonDictionary:(NSDictionary*)jsonDictionary {
    
    if (![jsonDictionary isKindOfClass: [NSDictionary class]]) {
        return;
    }
    
    NSObject *targetObject = self;
    
    while (targetObject.class != [NSObject class]) {
        
        unsigned int count = 0;
        //成员变量
        Ivar *ivars = class_copyIvarList(targetObject.class, &count);
        
        for (int i = 0; i < count; i++) {
            
            Ivar ivar = ivars[i];
            
            //  变量名称
            NSString *ivarName = [[NSString alloc] initWithUTF8String: ivar_getName(ivar)];
            
//            //  变量类型
//            NSString *ivarType = [NSString stringWithUTF8String:ivar_getTypeEncoding(ivar)];
//            NSLog(@"ivar = %@|%@", ivarType, ivarName);
            
            NSString* key = ivarName;
            ivarName = [ivarName substringFromIndex: 1];
            
            key = [key substringFromIndex: 1];
            
            if ([key hasPrefix: Prefix] && Prefix.length) {
                key = [key substringFromIndex: Prefix.length];
            }
            
            //  获取值
            id value = jsonDictionary[key];
            if (value != nil && ![value isKindOfClass: [NSNull class]]) {
                if ([value isKindOfClass: [NSNumber class]] || [value isKindOfClass: [NSString class]]) {
                    [self setValue: [value kk_stringValue] forKey: ivarName];
                }
                else {
                    [self setValue: value forKey: ivarName];
                }
            }
            else {
                
                NSString *ivarType = [NSString stringWithUTF8String:ivar_getTypeEncoding(ivar)];
                if ([ivarType isEqualToString: @"NSString"]) {
                    [self setValue: @"" forKey: ivarName];
                }
            }
        }
        free(ivars);
        
        targetObject = [targetObject.superclass new];
    }
}

- (NSString*)kk_stringValue {
    
    if ([self isKindOfClass: [NSNumber class]]) {
        return [NSString stringWithFormat: @"%@",self];
    }
    else if ([self isKindOfClass: [NSArray class]] || [self isKindOfClass: [NSDictionary class]]) {
        NSData *data = [NSJSONSerialization dataWithJSONObject: self options: NSJSONWritingPrettyPrinted error: nil];
        return [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
    }
    else if ([self isKindOfClass: [NSString class]]) {
        return (NSString*)self;
    }
    else if ([self isKindOfClass: [NSObject class]]) {
        return self.description;
    }
    else {
        return @"";
    }
}

#pragma mark - 正则表达式
+ (BOOL)isValidateEmail:(NSString *)email {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

+ (BOOL)isValidateMobile:(NSString*)mobile {
    NSString * MobileRegex = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MobileRegex];
    return [regextestmobile evaluateWithObject: mobile];
}

//  按照指定的对象去解析Json数组，并且返回对象数组
+ (NSArray*)kk_parserJsonArray:(NSArray*)jsonArray fromClassType:(Class)classType {
    
    if (![jsonArray isKindOfClass: [NSArray class]]) {
        return nil;
    }
    
    NSMutableArray *itemArray = [NSMutableArray array];
    for (NSDictionary *itemDictionary in jsonArray) {
        id object = [classType new];
        [object kk_parserJsonDictionary: itemDictionary];
        [itemArray addObject: object];
    }
    
    return itemArray;
}

//  按照指定的对象去解析Json字典，并且返回指定的对象类型
+ (id)kk_parserJsonDictionary:(NSDictionary*)jsonDictionary fromClassType:(Class)classType {
    
    id object = [classType new];
    [object kk_parserJsonDictionary: jsonDictionary];
    return object;
}

@end


@implementation NSObject(NSDate)

static NSDateFormatter* XKDateFormatter = nil;

+ (NSString*)dateStringDifferenceNowWithTime:(NSTimeInterval)timeInterval andWithDetailReturn:(BOOL)detail {
    
    NSString* dateString = nil;
    NSDate* publicDate = [NSDate dateWithTimeIntervalSince1970: timeInterval / 1000];
    
    if (XKDateFormatter == nil) {
        XKDateFormatter = [NSDateFormatter new];
        [XKDateFormatter setDateStyle: NSDateFormatterLongStyle];
    }
    
    if (detail) {
        [XKDateFormatter setDateFormat: @"HH:mm:ss yyyy-MM-dd"];
        dateString = [XKDateFormatter stringFromDate: publicDate];
    }
    else {
        
        NSTimeInterval offsetValue = [publicDate timeIntervalSinceNow];
        offsetValue = ABS(offsetValue);
        if (offsetValue < 3600.0 * 24 * 3) {
            if (offsetValue > 3600.0 * 48 && offsetValue < 3600.0 * 72) {
                dateString = @"前天";
            }
            else if (offsetValue > 3600.0 * 24 && offsetValue < 3600.0 * 48) {
                dateString = @"昨天";
            }
            else if (offsetValue < 3600.0) {
                NSInteger minute = offsetValue / 60;
                if (minute == 0) {
                    NSInteger seconds = (NSInteger)offsetValue;
                    seconds = seconds == 0 ? 1 : seconds;
                    dateString = [NSString stringWithFormat: @"%@秒前", @(seconds)];
                }
                else {
                    dateString = [NSString stringWithFormat: @"%@分钟前",@(minute)];
                }
            }
            else {
                NSInteger hour = offsetValue / 3600;
                dateString = [NSString stringWithFormat: @"%@小时前",@(hour)];
            }
        }
        else {
       
            [XKDateFormatter setDateFormat: @"yyyy-MM-dd"];
            dateString = [XKDateFormatter stringFromDate: publicDate];
        }
    }
    return dateString;
}

+ (NSString*)dateStringOfTime:(NSTimeInterval)timeInterval {
    
    return [self dateStringOfTime: timeInterval format: @"MM-dd"];
}

+ (NSString*)dateStringOfTime:(NSTimeInterval)timeInterval format:(NSString*)format {
    
    if (XKDateFormatter == nil) {
        XKDateFormatter = [NSDateFormatter new];
        [XKDateFormatter setDateStyle: NSDateFormatterLongStyle];
    }
    
    NSDate* publicDate = [NSDate dateWithTimeIntervalSince1970: timeInterval / 1000];
    
    [XKDateFormatter setDateFormat: format];
    return [XKDateFormatter stringFromDate: publicDate];
}

@end


@implementation NSData(Push)

- (NSString*)pushToken {
    
    NSString *tmpString = [self description];
    tmpString = [tmpString stringByReplacingOccurrencesOfString: @"<" withString: @""];
    tmpString = [tmpString stringByReplacingOccurrencesOfString: @">" withString: @""];
    tmpString = [tmpString stringByReplacingOccurrencesOfString: @" " withString: @""];
    return tmpString;
}

@end
